package com.example.hibernate.demo.controller;

import com.example.hibernate.demo.entity.*;
import com.example.hibernate.demo.repository.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import lombok.RequiredArgsConstructor;
import org.hibernate.Session;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 这个控制器展示了各种Hibernate的高级功能
 */
@RestController
@RequestMapping("/api/hibernate-examples")
@RequiredArgsConstructor
public class HibernateExamplesController {

    @PersistenceContext
    private EntityManager entityManager;
    
    private final EmployeeRepository employeeRepository;
    private final DepartmentRepository departmentRepository;
    private final ProjectRepository projectRepository;
    
    /**
     * 展示Hibernate会话和缓存
     */
    @GetMapping("/session-demo")
    @Transactional(readOnly = true)
    public ResponseEntity<Map<String, Object>> sessionDemo() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取Hibernate会话
        Session session = entityManager.unwrap(Session.class);
        
        // 第一次查询 - 从数据库加载
        Employee emp = employeeRepository.findById(1L).orElse(null);
        result.put("firstQuery", emp != null ? emp.getFirstName() + " " + emp.getLastName() : "Not found");
        
        // 第二次查询 - 从一级缓存加载
        Employee sameEmp = employeeRepository.findById(1L).orElse(null);
        result.put("secondQuery", sameEmp != null ? sameEmp.getFirstName() + " " + sameEmp.getLastName() : "Not found");
        
        // 清除会话缓存
        session.clear();
        
        // 第三次查询 - 再次从数据库加载
        Employee empAfterClear = employeeRepository.findById(1L).orElse(null);
        result.put("thirdQuery", empAfterClear != null ? empAfterClear.getFirstName() + " " + empAfterClear.getLastName() : "Not found");
        
        return ResponseEntity.ok(result);
    }
}